from docxtpl import DocxTemplate
import os

# 1. 加载模板
tpl = DocxTemplate("模板.docx")

# 2. 准备 3 个学生的数据
students = [
    {
        "name": "张三",
        "courses": [
            {"course": "数学", "score": 90},
            {"course": "英语", "score": 85},
            {"course": "物理", "score": 72}
        ]
    },
    {
        "name": "李四",
        "courses": [
            {"course": "数学", "score": 88},
            {"course": "英语", "score": 92},
            {"course": "物理", "score": 79}
        ]
    },
    {
        "name": "王五",
        "courses": [
            {"course": "数学", "score": 75},
            {"course": "英语", "score": 83},
            {"course": "物理", "score": 91}
        ]
    }
]

# 3. 创建“考试成绩”文件夹（如果不存在）
output_dir = "考试成绩"
os.makedirs(output_dir, exist_ok=True)

# 4. 遍历学生数据，批量生成 Word
for stu in students:
    context = {
        "name": stu["name"],
        "courses": stu["courses"]
    }
    tpl.render(context)                # 渲染
    file_path = os.path.join(output_dir, f"{stu['name']}.docx")
    tpl.save(file_path)                # 保存到“考试成绩”文件夹
    print(f"已生成：{file_path}")